<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="Username" prop="username">
      <el-input v-model="ruleForm.username" autocomplete="off" />
    </el-form-item>
    <el-form-item label="Phone" prop="phone">
      <el-input v-model="ruleForm.phone" autocomplete="off" />
    </el-form-item>
    <el-form-item label="Password" prop="password">
      <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item label="Confirm Password" prop="confirmPassword">
      <el-input v-model="ruleForm.confirmPassword" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">Submit</el-button>
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import axios from 'axios'

const ruleFormRef = ref<FormInstance>()

// 验证手机号
const checkPhone = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('Please input the phone number'))
  }
  // 这里可以添加更复杂的手机号验证逻辑
  if (!/^\d{11}$/.test(value)) {
    return callback(new Error('Invalid phone number'))
  }
  callback()
}

// 验证两次密码是否一致
const checkPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    return callback(new Error('Please input the password again'))
  }
  if (value !== ruleForm.password) {
    return callback(new Error("Two inputs don't match!"))
  }
  callback()
}

const ruleForm = reactive({
  username: '',
  phone: '',
  password: '',
  confirmPassword: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ required: true, message: 'Please input the username', trigger: 'blur' }],
  phone: [{ required: true, validator: checkPhone, trigger: 'blur' }],
  password: [{ required: true, message: 'Please input the password', trigger: 'blur' }],
  confirmPassword: [{ required: true, validator: checkPassword, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      axios.post('/login', {
        username: ruleForm.username,
        phone: ruleForm.phone,
        password: ruleForm.password
      })
      .then(response => {
        // 处理登录成功逻辑
        console.log('登录成功', response);
        // 可能需要保存 token 或跳转到其他页面
      })
      .catch(error => {
        // 处理登录失败逻辑
        console.error('登录失败', error);
      });
    } else {
      console.log('表单验证失败，不能提交')
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>